<template>
  <div class="app-container bg">
    <div class="box-container">
      <div class="mb15">
        <el-radio-group v-model="showType" @change="showTypeChange">
          <el-radio-button label="1">科室</el-radio-button>
          <el-radio-button label="2">学员</el-radio-button>
        </el-radio-group>
      </div>

      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="font-size: 14px; line-height: 25px"
      >
        <el-col :span="2.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ registerBaseVo.total || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(1, 1)"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            待审批：{{ registerBaseVo.graduationAuditStatus1 || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(3, 3)"
            class="nactive"
            :class="{ active: tagIndex == 3 }"
          >
            已通过：{{ registerBaseVo.graduationAuditStatus3 || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(4, 4)"
            class="nactive"
            :class="{ active: tagIndex == 4 }"
          >
            已拒绝：{{ registerBaseVo.graduationAuditStatus4 || 0 }}
          </div>
        </el-col>
      </el-row>

      <el-row v-if="showType == 2" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            :disabled="multiple"
            type="primary"
            size="mini"
            @click="auditOpen"
            >批量审批</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          format="yyyy"
          style="width: 160px"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.total }}
              <div class="desc">录取总数</div>
            </div>
            <div class="col">
              {{ row.graduationAuditStatus1 }}
              <div class="desc">待审批</div>
            </div>
            <div class="col">
              <span class="red">{{ row.graduationAuditStatus4 }}</span>
              <div class="desc">已拒绝</div>
            </div>
            <div class="col">
              {{ row.graduationAuditStatus3 }}
              <div class="desc">已通过</div>
            </div>
            <div class="col">
              {{ row.graduationAuditStatus2 }}
              <div class="desc">转审中</div>
            </div>
          </div>

          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="col border" style="display: flex; flex: 8">
            <div class="user-name">
              <div style="display: flex; align-items: center">
                <div style="margin-right: 10px">
                  <el-checkbox
                    v-model="row.check"
                    style="transform: scale(1.2)"
                    @change="handleSelectionChange($event, index)"
                  />
                </div>
                <span
                  style="
                    font-size: 18px;
                    font-weight: bolder;
                    color: #a52529;
                    cursor: pointer;
                  "
                  @click="detailOpen(row)"
                  >{{ row.userName }}</span
                >
              </div>
              <div style="margin-left: auto; font-size: 12px; color: #999">
                工号：{{ row.jobNumber }}
              </div>
            </div>
            <div class="info">
              <div class="flexInfo left">
                <div>进修科目：{{ row.registerDeptName }}</div>
                <div style="display: flex">
                  进修期限：
                  <div v-if="row.registerNoticeVo">
                    {{ row.registerNoticeVo.startDate }} -

                    {{ row.registerNoticeVo.endDate }}
                    <span v-if="row.durationName"
                      >（{{ row.durationName }}）</span
                    >
                  </div>
                </div>
                <div>记录手册完成度：{{ row.manualTotal }}%</div>
                <div>
                  考勤情况：{{
                    (row.registerLeaveVoList || []).length == 0
                      ? "全勤"
                      : `请假${(row.leaveStat || {}).leaveDays}天 销假${
                          (row.leaveStat || {}).closeDays
                        }天`
                  }}
                </div>
              </div>
              <div class="flexInfo right">
                <div>
                  报到时间：{{
                    parseTime(
                      row.registerNoticeVo && row.registerNoticeVo.sureTime,
                      "{yyyy}/{mm}/{dd} {hh}:{ii}:{ss}"
                    )
                  }}
                </div>
                <div>考评分数：{{ row.scoreTotal }}</div>
                <div>考评等级：{{ row.scoreLevel }}</div>
                <div style="display: flex; align-items: center">
                  结业时间：{{ row.registerNoticeVo.endDate }}
                  <div v-if="row.leaveStatusDesc" style="color: #a52529">
                    （{{ row.leaveStatusDesc }}）
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col border">
            <img
              src="../../../../assets/images/biezhen.png"
              style="width: 40px; height: 40px"
            />
            <el-button size="mini" type="text" @click="historyOpen(row)"
              >审批历史
            </el-button>
          </div>
          <div class="col border">
            <div class="desc">审批状态</div>
            <div class="systemColor">
              {{ row.graduationAuditStatusName }}
            </div>
          </div>
          <div class="col border">
            <i
              class="el-icon-document-copy systemColor"
              style="font-size: 30px"
            ></i>
            <el-button size="mini" type="text" @click="revokeOpen(row)"
              >申请详情
            </el-button>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="批量审批"
      :visible.sync="auditShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审批状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">同意</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="审批意见"
          :prop="auditForm.auditStatus !== 1 ? 'remark' : null"
        >
          <el-input
            type="textarea"
            :rows="5"
            v-model="auditForm.remark"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="auditFormSubmit">确 定</el-button>
        <el-button @click="auditShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="记录手册"
      :visible.sync="detailShow"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
      @close="graduationClose"
    >
      <registerManual
        v-if="detailShow"
        :onlyread="true"
        :register-id="registerId"
        @close="graduationClose"
      />
    </el-dialog>

    <el-dialog
      title="结业申请"
      :visible.sync="graduationShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerGraduation
        v-if="graduationShow"
        :register-id="registerId"
        @openManual="detailShow = true"
        @close="graduationClose"
      />
    </el-dialog>

    <el-dialog
      title="审批历史"
      :visible.sync="graduationHistoryShow"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerGraduationHistory
        v-if="graduationHistoryShow"
        :register-id="registerId"
        @close="graduationClose"
      />
    </el-dialog>
    <el-dialog
      title="报名详情"
      :visible.sync="detailShowInfo"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShowInfo"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShowInfo = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  queryByCountRegisterBase,
  queryByDeptRegisterBase,
  saveGraduationRegisterBase,
} from "@/api/business/registerBase";

import { setupBatchData } from "@/utils/batchUtils";

import { listAllRegisterDept } from "@/api/business/registerDept";
import { delRegisterInfo, listRegisterInfo } from "@/api/business/registerInfo";
import { listAllRegisterType } from "@/api/business/registerType";
import registerGraduation from "@/views/business/registerBase/audit/components/registerGraduation.vue";
import registerGraduationHistory from "@/views/business/registerBase/audit/components/registerGraduationHistory.vue";
import registerManual from "@/views/business/registerBase/audit/components/registerManual";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";

/**
 * 结业管理组件
 * 功能：
 * 1. 展示科室/学员的结业审批状态统计
 * 2. 提供批量审批功能
 * 3. 查看学员结业申请详情
 * 4. 查看审批历史记录
 */
export default {
  name: "graduation",
  components: {
    registerGraduation,
    registerManual,
    registerGraduationHistory,
    registerInfoDetailInfo,
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 招生信息表格数据
      dataList: [],
      //全选
      AllCheck: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 报到状态已报到
        sureStatus: 2,
        payNoRefund: 1,
        graduationAuditStatus: null,
        graduationAuditStatusList: [1, 2, 3, 4],
        graduationStatusList: [0, 1, 2, 4],
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
      },
      detailShowInfo: false, // 报到详情
      registerInfo: {
        id: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: consts.registerBatchList,
      registerBaseVo: {},
      // 页面显示
      showType: 1,
      // 批量审批
      auditShow: false,
      auditForm: {},
      auditRules: {
        auditStatus: [
          { required: true, message: "审批状态不能为空", trigger: "blur" },
        ],
        remark: [
          { required: true, message: "审批意见不能为空", trigger: "blur" },
        ],
      },
      registerId: null,
      // 记录手册
      detailShow: false,
      // 结业申请
      graduationShow: false,
      // 审批历史
      graduationHistoryShow: false,
      tagIndex: 0,
    };
  },
  async created() {
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    async getbatch() {
      await setupBatchData(this);
    },
    /**
     * 初始化数据
     * 1. 获取统计计数
     * 2. 获取列表数据
     */
    initData() {
      this.getCount();
      this.getList();
    },
    clickAll(index, value) {
      this.canselAllcheck();

      this.tagIndex = index;
      this.queryParams.graduationAuditStatus = value;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    /**
     * 获取各状态统计计数
     * @returns {Promise<void>}
     */
    getCount() {
      queryByCountRegisterBase(this.queryParams).then((response) => {
        if (response.data) {
          this.registerBaseVo = response.data;
          this.registerBaseVo.total = this.calculateTotalStatus(
            this.registerBaseVo
          );
        }
      });
    },
    /**
     * 获取列表数据
     * 根据showType不同展示科室或学员视图
     * @returns {Promise<void>}
     */
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        queryByDeptRegisterBase(this.queryParams).then((response) => {
          this.dataList = response.rows;
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].total =
              this.dataList[i].graduationAuditStatus1 +
              this.dataList[i].graduationAuditStatus2 +
              this.dataList[i].graduationAuditStatus3 +
              this.dataList[i].graduationAuditStatus4;
          }
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.showType == 2) {
        listRegisterInfo(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.dataList.forEach((item) => {
            let manualTotal = 0;
            // 1、进修计划：完成进修计划，获得20%进度
            let progress = this.getTimeProgress(
              item.registerNoticeVo.startDate,
              item.registerNoticeVo.endDate
            );
            if (progress === 100) {
              manualTotal += 20;
              console.log(1);
            }
            // 2、进修考评：完成带教出科考评与考评结论，获得20%进度
            let registerAllocationVoList = item.registerAllocationVoList;
            if (
              registerAllocationVoList.length > 0 &&
              registerAllocationVoList.filter((e) => {
                return e.scoreStatus === 2;
              }).length === registerAllocationVoList.length
            ) {
              manualTotal += 20;
              console.log(2);
            }
            let registerManualVo = item.registerManualVo;
            if (registerManualVo) {
              // 3、个人小结：完成个人小结填写，获得20%进度
              if (registerManualVo.personalSummary) {
                manualTotal += 20;
              }
              // 4、临床工作：完成个人小结填写，获得20%进度
              if (
                registerManualVo.clinicNumber ||
                registerManualVo.emergencyNumber ||
                registerManualVo.averageNumber ||
                registerManualVo.clinicEmergencyContent ||
                registerManualVo.manageBeds ||
                registerManualVo.caseNumber ||
                registerManualVo.wardContent ||
                registerManualVo.businessContent ||
                registerManualVo.otherContent
              ) {
                manualTotal += 20;
                console.log(4);
              }
              // 5、进修评价：完成进修评价填写，获得20%进度
              if (
                registerManualVo.introduceFlag &&
                registerManualVo.planFlag &&
                registerManualVo.environmentFlag &&
                registerManualVo.teacherFlag &&
                registerManualVo.businessFlag &&
                registerManualVo.timecardFlag &&
                registerManualVo.examineFlag &&
                registerManualVo.strengthContent &&
                registerManualVo.improveContent
              ) {
                manualTotal += 20;
                console.log(5);
              }
            }
            item.manualTotal = manualTotal;
          });
          this.loading = false;
        });
      }
    },
    // 批量审批
    auditOpen() {
      let list = this.dataList.filter((e) => this.ids.indexOf(e.id) > -1);
      for (let i = 0; i < list.length; i++) {
        if (
          list[i].graduationAuditStatus != 1 &&
          list[i].graduationAuditStatus != 2
        ) {
          this.$modal.msgError("请选择审批状态为待审批或转审中的数据");
          return;
        }
      }
      this.auditForm = {
        registerIdList: this.ids,
        auditStatus: 1,
        remark: null,
      };
      this.auditShow = true;
    },
    auditFormSubmit() {
      this.$refs["auditForm"].validate((valid) => {
        if (valid) {
          saveGraduationRegisterBase(this.auditForm).then((response) => {
            this.$modal.msgSuccess("审批成功");
            this.initData();
            this.auditShow = false;
          });
        } else {
          this.$modal.msgError("请完善表单内容");
        }
      });
    },
    detailOpen(row) {
      this.registerInfo.id = row.id;
      this.detailShowInfo = true;
    },
    graduationClose() {
      this.initData();
      this.detailShow = false;
      this.graduationShow = false;
    },
    // 结业申请
    revokeOpen(row) {
      this.registerId = row.id;
      this.graduationShow = true;
    },
    // 审批历史
    historyOpen(row) {
      this.registerId = row.id;
      this.graduationHistoryShow = true;
    },
    // 查看名单
    viewOpen(row) {
      this.showType = 2;
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    // 删除
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除报名信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegisterInfo(ids);
        })
        .then(() => {
          this.initData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 切换视图
    showTypeChange() {
      this.canselAllcheck();

      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.canselAllcheck();

      this.queryParams.pageNum = 1;
      this.initData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.canselAllcheck();

      this.resetForm("queryForm");
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    // 全选
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
      console.log(this.multiple);
      console.log(this.single);
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      console.log(checked, index);
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    /**
     * 计算总状态数
     * @param {Object} data - 包含各状态计数的对象
     * @returns {Number} 各状态计数之和
     */
    calculateTotalStatus(data) {
      return (
        data.graduationAuditStatus1 +
        data.graduationAuditStatus2 +
        data.graduationAuditStatus3 +
        data.graduationAuditStatus4
      );
    },

    /**
     * 计算时间进度百分比
     * @param {String} startDateStr - 开始日期字符串 (格式: yyyy-MM-dd)
     * @param {String} endDateStr - 结束日期字符串 (格式: yyyy-MM-dd)
     * @returns {Number} 进度百分比 (0-100)
     */
    getTimeProgress(startDateStr, endDateStr) {
      const startDate = new Date(startDateStr.replace(/-/g, "/"));
      const endDate = new Date(endDateStr.replace(/-/g, "/"));
      const now = new Date();
      if (now < startDate) {
        return 0;
      }
      if (now.getTime() >= endDate.getTime() - 12096e5) {
        return 100;
      }
      const totalDuration = endDate.getTime() - startDate.getTime();
      const elapsedDuration = now.getTime() - startDate.getTime();
      const progressPercentage = (elapsedDuration / totalDuration) * 100;
      return progressPercentage.toFixed(2);
    },
  },
};
</script>
<style lang="scss" scoped>
// 基础变量定义
$border-color: #d8d8d8;
$primary-color: #a52529;
$secondary-color: #606266;
$light-gray: #eeeff4;
$desc-color: #888;

// 通用样式
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

// 用户名称样式
.user-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 5px;
}

// 容器基础样式
.box-container {
  padding: 0 0 0 20px;
}

// 弹性布局容器
.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  background: $light-gray;
  padding: 20px 0;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

// 自定义表格样式
.custom-table {
  // 科室行样式
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid $border-color;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 6);

      // 描述文字样式
      .desc {
        font-size: 12px;
        color: $desc-color;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    &:hover {
      border-color: red;
    }
  }

  // 学员注册行样式
  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    // 信息区域样式
    .info {
      display: flex;
      justify-content: space-between;
      color: $secondary-color;
      font-size: 14px;
      width: 100%;
      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        box-sizing: border-box;
        line-height: 20px;
        &.left {
          flex: 1;
        }

        &.right {
          width: 260px;
        }
      }
    }

    // 边框样式
    .border {
      border: 1px solid rgba(153, 153, 153, 0.15);
      padding: 10px;
      height: 100%;
      display: flex;
      flex-direction: column;
      font-size: 12px;

      .desc {
        margin-bottom: 10px;
      }
    }

    // 列样式
    .col {
      .desc {
        color: #666;
        margin-top: 10px;
        font-weight: normal;
      }

      &:nth-child(1) {
        width: calc(100% - 400px);
        text-align: left;
      }

      &:nth-child(2),
      &:nth-child(3),
      &:nth-child(4),
      &:nth-child(5) {
        width: 130px;
      }
    }
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
}
</style>
